package com.oceansoft.mobile.biz.api.controller;

import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.admin.service.ISysUserService;
import com.oceansoft.mobile.biz.api.entity.AuthUser;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.common.util.StringUtils;
import com.oceansoft.mobile.weixin.util.DesUtil;
import com.oceansoft.mobile.weixin.util.RequestUtils;
import com.oceansoft.mobile.weixin.util.WeixinUtil;

@Controller
@RequestMapping("api/account")
public class ApiLoginOrRegisterController {


	@Resource
	private ISysUserService sysUserService;

	@ResponseBody
	@RequestMapping(value="auth")
	public Result apiAuth(HttpServletRequest request) throws IllegalArgumentException, Exception {
		Map<String, String> param = new HashMap<String, String>();
		param= RequestUtils.buildParamsByNamesFromRequest(request);
		param.put("UserSource","3");//登陆时指明微信端登陆1：办事大厅2：交管3：微信4：APP
		DesUtil tools = new DesUtil();
		param.put("PASSWORD", tools.encode(param.get("PASSWORD").toString()));
		System.out.println("param===="+param);
		String url=Constant.host5+"api/Users/UserLogin";
		Result re= JSONObject.parseObject(HttpClientUtil.doPost(url, param, "utf-8"), Result.class);
		System.out.println(JSONObject.toJSON(re));
		if(re.isSucc()){
			re.setMsg("登陆成功");
			Member member = new Member();
			member =WeixinUtil.SetMember(JSONObject.parseObject(re.getData().toString()));
			request.getSession().setAttribute(Constant.SESSION_USER,member);
		}else
		{
			 param.put("UserSource","4");
			 re= JSONObject.parseObject(HttpClientUtil.doPost(url, param, "utf-8"), Result.class);
			 System.out.println(JSONObject.toJSON(re));
			 if(re.isSucc()){
				 re.setMsg("登陆成功");
				Member member = new Member();
				member =WeixinUtil.SetMember(JSONObject.parseObject(re.getData().toString()));
				request.getSession().setAttribute(Constant.SESSION_USER,member);
			 }
			 else
			 {
				 param.put("UserSource","1");
				 re= JSONObject.parseObject(HttpClientUtil.doPost(url, param, "utf-8"), Result.class);
				 System.out.println(JSONObject.toJSON(re));
				 if(re.isSucc()){
					 re.setMsg("登陆成功");
					Member member = new Member();
					member =WeixinUtil.SetMember(JSONObject.parseObject(re.getData().toString()));
					request.getSession().setAttribute(Constant.SESSION_USER,member);
				 }
			 }
		}
		re.setData(request.getSession().getAttribute(Constant.SESSION_USER));
		return 	re;
		//return new Result(Result.FAILURE);
	//	return "weixin/login/login";
	}

	@ResponseBody
	@RequestMapping(value="registersubmit",method= RequestMethod.GET)
	public Result apiRegistersubmit(@RequestParam("jsondata") String jsondata,HttpServletRequest request) throws IllegalArgumentException, Exception {
		jsondata = URLDecoder.decode(jsondata,"utf-8");
		String openId=(String)request.getSession().getAttribute("openId"); //WeixinUtil.getOpenId(request);;//"20881011910123570328892602119985",
		Map<String, String> param = new HashMap<String, String>();
		DesUtil tools = new DesUtil();
		JSONObject json=JSONObject.parseObject(jsondata);
		param.put("USERCODE", tools.encode(json.get("USERCODE").toString()));
		param.put("YZM", json.get("YZM").toString());
		param.put("PASSWORD", tools.encode(json.get("PASSWORD").toString()));
		param.put("OpenId",openId);
		String UserSource = request.getParameter("UserSource");
		if(StringUtils.isEmpty(UserSource))
		{
			UserSource = "3";
		}
		param.put("UserSource",UserSource);
		param.put("USERTYPE","1");
		param.put("LINKNAME",json.get("ALIASNAME").toString());
		param.put("MOBILE", tools.encode(json.get("USERNAME").toString()));
		param.put("USERNAME",json.get("USERNAME").toString());
		param.put("ADDRESS",json.get("ADDRESS").toString());
		param.put("ALIASNAME",json.get("ALIASNAME").toString());
		param.put("AVATARURL",json.get("AVATARURL").toString());//0表明是市局微警务注册，五县市分为1-5
		String url=Constant.host5+"api/Users/UserReg";
		Result result = JSONObject.parseObject(HttpClientUtil.doPost(url, param,"utf-8"), Result.class);
		if (result.isSucc()){
			result.setMsg("注册成功");
			Member member = (Member) WeixinUtil.SetMember(JSONObject.parseObject(result.getData().toString()));
			AuthUser user = new AuthUser();
			user.setOpenId(openId);
			user.setUserId(member.getGuid());
			user.setUpdateTime(new Date());
			sysUserService.saveWeChatUser(user);
		}
		return 	result;
		//return new Result(Result.FAILURE);
		//	return "weixin/login/login";
	}

	@ResponseBody
	@RequestMapping(value="sendMess",method= RequestMethod.GET)
	public Result apisendMess(final HttpServletRequest request) throws IllegalArgumentException, Exception {
//		String openId=String.valueOf(Math.random()*10000000); //WeixinUtil.getOpenId(request);;//"20881011910123570328892602119985",
//		JSONObject json=new JSONObject();
//		json.put("tel", tel);
//		json.put("type", String.valueOf(Constant.SMS_BIZ_REGISTER));
		String tel = request.getParameter("tel");
		DesUtil tools = new DesUtil();
		String url=Constant.host5+"api/User/GetCode?Phone="+tel;
		String a = HttpClientUtil.doGet(url);
		JSONObject jsona=JSONObject.parseObject(a);
		Result re=new Result(Result.SUCC);
		re.setData(jsona.get("ResultData"));
		return 	re;
		//return new Result(Result.FAILURE);
		//	return "weixin/login/login";
	}
	@ResponseBody
	@RequestMapping(value="pwd/reset")
	public Result apiWjmm(HttpServletRequest request) throws IllegalArgumentException, Exception {
		Map<String, String> param = new HashMap<String, String>();
		DesUtil tools = new DesUtil();
		String url=Constant.host5+"api/User/GetBackPwd";
		param= RequestUtils.buildParamsByNamesFromRequest(request);
		param.put("Usercards", tools.encode(param.get("Usercards")));
		param.put("phones", tools.encode(param.get("phones")));
		//把身份转成小写，如果查询正确直接返回，不正确查询大写
		Result result = JSONObject.parseObject((HttpClientUtil.doPost(url, param, "utf-8")), Result.class);
//		if(!result.isSucc()){
//			param.put("id",param.get("id").toUpperCase());
//			Result result1=JSONObject.parseObject((HttpClientUtil.doPost(url, param, "utf-8")), Result.class);
//			return result1;
//		}
		return 	result;
	}


	@RequestMapping("login")
	public String apiLogin(HttpServletRequest request, Model model){
		String source = request.getParameter("source");
		
	       if (!StringUtils.isEmpty(source)) {
	       	model.addAttribute("source", source);
	       }
		return "weixin/login/login";

	}
	@RequestMapping("register")
	public String apiRegister(HttpServletRequest request, Model model){
		String source = request.getParameter("source");
	       if (!StringUtils.isEmpty(source)) {
	       	model.addAttribute("source", source);
	       }
		return "weixin/login/register";
	}
	@RequestMapping("register_protocol")
	public String apiregister_protocol(HttpServletRequest request, Model model){
		String source = request.getParameter("source");
	       if (!StringUtils.isEmpty(source)) {
	       	model.addAttribute("source", source);
	       }
		return "weixin/login/yhzcxy";

	}
	@RequestMapping("forget_password")
	public String apiforget_password(HttpServletRequest request, Model model){
		String source = request.getParameter("source");
	       if (!StringUtils.isEmpty(source)) {
	       	model.addAttribute("source", source);
	       }
		return "weixin/login/wjmm";
	}
	@RequestMapping(value = "gotopage/{pageName}")
	public String gotoMattersPage(@PathVariable("pageName") String pageName,HttpServletRequest request, Model model) {
		String source = request.getParameter("source");
		String gotoPage =request.getParameter("gotoPage");
		if (!StringUtils.isEmpty(source)) {
			model.addAttribute("source", source);
		}
//		if(pageName.contains("hclstxz")||pageName.contains("sgcltxz")){
//			Member member = (Member)session.getAttribute(Constant.SESSION_USER);
//			if(null!=member){
//				model.addAttribute("userId",member.getGuid());
//				model.addAttribute("xzfy",request.getSession().getAttribute("xzfy"));
//			}
//
//		}
		model.addAttribute("gotoPage", gotoPage);
		return "weixin/login/" + pageName;
	}
	
	@RequestMapping(value="getOpenId")
	public String getOpenId(HttpServletRequest request) {
//		Result result =new Result();
		String openId=(String)request.getSession().getAttribute("openId");//
		String page  = request.getParameter("page");
		if(StringUtils.isEmpty(page))
		{
			return Constant.stateMap.get("0");
		}
		else 
		{
			if(!page.startsWith("http"))
			{
				page = "http://" + page;
			}
		} 
		
		if(page.indexOf("?")>10)
		{
			page =  page+"&openId="+openId ;
		}
		else
		{
			page =  page+"?openId="+openId ; 
		}
		return "redirect:" + page;
	}
	
}
